import java.util.Iterator;

/*
 * @lc app=leetcode.cn id=482 lang=java
 *
 * [482] 密钥格式化
 */

// @lc code=start
class Solution {
    public String licenseKeyFormatting(String S, int K) {
        
        if(K<0) return "";
        StringBuilder builder = new StringBuilder();
        for(int i = 0 ;i<S.length();i++){
            if(S.charAt(i)!='-')
               builder.append(S.charAt(i));
        }
        for(int i=builder.length()-K;i>0;i-=K){//最后一次可能i变成负数了
            builder.insert(i, '-');
        }

        return builder.toString().toUpperCase();
    }
}
// @lc code=end

